package com.mlm.mlmapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.mlm.mlmapp.utils.StringEncrypt;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.userinfo)
public class UserInfoActivity extends BaseActivity {

    AQuery aq;
    public final static int FORWARD_TYPE_COUPON=99;
    public final static int FORWARD_TYPE_COLLECTION=1;
    public final static int FORWARD_TYPE_POINT=2;
    public final static int FORWARD_TYPE_ORDERS_ALL=3;
    public final static int FORWARD_TYPE_ORDERS_UNPAY=4;
    public final static int FORWARD_TYPE_ORDERS_SUCCESS=5;
    public final static int FORWARD_TYPE_ORDERS_COMPLETE=6;
    public final static int FORWARD_TYPE_ORDERS_REFUND=7;
    public final static int FORWARD_TYPE_COMMENT=8;
    public final static int FORWARD_TYPE_ACCOUNT_SETTING=9;
    public final static int FORWARD_TYPE_SIGNIN=10;
    public final static int FORWARD_TYPE_PROMOTION=11;
    @Pref
    Prefs_ pref;
    @StringRes
    String msg_error;
    @ViewById
    ImageView iv_headimg;
    @ViewById
    TextView tv_coupon;
    @ViewById
    Button btn_coupon;
    @ViewById
    Button btn_sign;
    @ViewById
    TextView tv_points;
    @ViewById
    Button btn_points;
    @ViewById
    Button btn_about_us;
    @ViewById
    Button btn_ads;
    @ViewById
    TextView tv_collections;
    @ViewById
    Button btn_collections;
    @ViewById
    TextView tv_username;
    @ViewById
    Button btn_unpay;
    String proxyInfoId;
    ActionSheetDialog dialog;
    @StringRes
    String take_photo;
    @StringRes
    String from_photos;
    @ColorRes
    int red;
    @ColorRes
    int blacktext;
    public static final String IMAGE_FILE_NAME = "avatar.jpg";
    AjaxCallback<JSONObject> uploadHeadimg;
    private Bitmap photo;
    String username;
    private int orders;
    private String currentHeadUrl;
    @DrawableRes
    Drawable headdef;

    @Click
    void ll_points() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_POINT).startForResult(REQUEST_CODE);
        } else {
            PointListActivity_.intent(this).start();
        }
//        PointListActivity_.intent(this).start();
    }

    @Click
    void btn_buy() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).startForResult(REQUEST_CODE);
        } else {
            BuyPointListActivity_.intent(this).start();
        }
    }

    @OnActivityResult(REQUEST_CODE)
    void onResult(int resultcode, Intent data) {
        if (resultcode == RESULT_CANCELED) {
            return;
        }
        if (data != null) {

            if (data.getBooleanExtra("flag", false)) {
                update();
                int type=data.getIntExtra("forward_type",-1);
                switch (type){
                    case FORWARD_TYPE_POINT:
                        PointListActivity_.intent(this).start();
                        break;
                    case FORWARD_TYPE_COLLECTION:
                        CollectionsActivity_.intent(this).start();
                        break;
                    case FORWARD_TYPE_COMMENT:
                        MyCommentsListActivity_.intent(this).start();
                        break;
                    case FORWARD_TYPE_COUPON:
                        CouponMineActivity_.intent(this).start();
                        break;
                    case FORWARD_TYPE_ORDERS_ALL:
                        OrdersActivity_.intent(this).extra("flag", OrdersActivity.TYPE_ALL)
                                .start();
                        break;
                    case FORWARD_TYPE_ORDERS_UNPAY:
                        OrdersActivity_.intent(this)
                                .extra("flag", OrdersActivity.TYPE_NONPAY).start();
                        break;
                    case FORWARD_TYPE_ORDERS_SUCCESS:
                        OrdersActivity_.intent(this)
                                .extra("flag", OrdersActivity.TYPE_BOOKED).start();
                        break;
                    case FORWARD_TYPE_ORDERS_COMPLETE:
                        OrdersActivity_.intent(this)
                                .extra("flag", OrdersActivity.TYPE_BOOKED).start();
                        break;
                    case FORWARD_TYPE_ORDERS_REFUND:
                        OrdersActivity_.intent(this)
                                .extra("flag", OrdersActivity.TYPE_REFUND).start();
                        break;
                    case FORWARD_TYPE_ACCOUNT_SETTING:
                        break;
                    case FORWARD_TYPE_PROMOTION:
                        String key = StringEncrypt.Encrypt("mobile=" + pref.loginID().get() + "&key=3e9bb86c6980c3b79e5b936ce10b9b96", "SHA-256");
                        Intent intent = new Intent();
//            intent.putExtra("url", "http://share.mlmsalon.com/Home/Partner/index/mobile/" + pref.loginID().get() + "/sign/" + key);
                        intent.putExtra("url", webhost + "/Home/Partner/index/mobile/" + pref.loginID().get() + "/sign/" + key);
                        intent.putExtra("proxyInfoId", proxyInfoId);
                        intent.putExtra("mobile", pref.loginID().get());
                        intent.setClass(this, ShowWebView_.class);
                        startActivity(intent);
                        break;
                    case FORWARD_TYPE_SIGNIN:
                        String signkey = StringEncrypt.Encrypt("mobile=" + pref.loginID().get() + "&key=3e9bb86c6980c3b79e5b936ce10b9b96", "SHA-256");
                        Intent signintent = new Intent();
                        signintent.putExtra("url", webhost + "/Home/Activity/sign/mobile/" + pref.loginID().get() + "/sign/" + signkey);
                        signintent.setClass(this, ShowWebView_.class);
                        startActivity(signintent);
                        break;
                    default:

                }
            } else {
//                this.finish();
            }
        }
    }

    @OnActivityResult(AN_REQUEST_CODE)
    void onResultAN(int resultcode,Intent data) {
        if(resultcode==RESULT_CANCELED){
            iv_headimg.setImageResource(R.drawable.headdef);
            tv_username.setText("未登录");
            tv_collections.setText("0");
            tv_coupon.setText("0");
            tv_points.setText("0");
            btn_unpay.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.unpay), null, null);
            return;
        }
        if(data.getBooleanExtra("modifyflag",false)){
            String mobile=pref.loginID().get();
            pref.loginID().remove();
            pref.proxyID().remove();
            LoginActivity_.intent(this).extra("mobile",mobile).extra("modifyloginflag",true).startForResult(AN_REQUEST_CODE);
            return;
        }
        update();
    }

    @AfterViews
    void init() {
        btn_userinfo.setCompoundDrawablesWithIntrinsicBounds(null,
                getResources().getDrawable(R.drawable.mychecked), null, null);
        btn_userinfo.setTextColor(getResources().getColor(R.color.red));
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }
//        btn_unpay.setVisibility(View.INVISIBLE);
//        setTranStatusBar();
        aq = new AQuery(this);
        if ("0".equals(pref.loginID().get())) {
            // LoginActivity_.intent(this).startForResult(REQUEST_CODE);
        } else {
            update();
        }
        uploadHeadimg = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(UserInfoActivity.this, "网络异常,请检查网络", Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {
                            Toast.makeText(aq.getContext(), "上传成功",
                                    Toast.LENGTH_SHORT).show();
                            iv_headimg.setImageBitmap(photo);
                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };


    }


    private void update() {
        AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), msg_error,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {

                    // MainActivity_.intent(LoginActivity.this).start();
                    // userName iconPhotoUrl mobile balance integral
                    // collecNum couponNum

                    tv_username.setText(CommonUtils.getJsonString(html,
                            "userName"));
                    orders = CommonUtils.getJsonInt(html,
                            "orders");
                    if (orders > 0) {
                        btn_unpay.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.unpay_tip), null, null);
                    } else {
                        btn_unpay.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.unpay), null, null);
                    }
                    username = CommonUtils.getJsonString(html,
                            "userName");
                    tv_points.setText(CommonUtils.getJsonString(html,
                            "integral"));
                    tv_collections.setText(CommonUtils.getJsonString(html,
                            "collecNum"));
                    tv_coupon.setText(CommonUtils.getJsonString(html,
                            "couponNum"));
                    proxyInfoId = CommonUtils.getJsonString(html,
                            "proxyInfoId");
                    pref.edit().proxyID().put(proxyInfoId).apply();
                    if ("".equals(CommonUtils.getJsonString(html,
                            "iconPhotoUrl"))) {
                        iv_headimg.setImageResource(R.drawable.headdef);
                    } else {
                            aq.id(iv_headimg)
                                    .image(CommonUtils.getJsonString(html,
                                            "iconPhotoUrl"),
                                            false,
                                            true,
                                            200,
                                            0,
                                          null,
                                            0);

                    }

                }
            }
        };
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        // pairs.add(new BasicNameValuePair("mobile", "18245189375"));

        CommonUtils.postRequest(get_user_info_action, aq, cb, pairs);
    }

    @Click
    void tv_username() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("username", "1").startForResult(REQUEST_CODE);
        } else {
            // update();
            ModifyNickNameActivity_.intent(this).extra("oldname", username).startForResult(REQUEST_CODE);
        }

    }
    @Click
    void ll_coupon() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_COUPON).extra("username", "1").startForResult(REQUEST_CODE);
        } else {
            // update();
            CouponMineActivity_.intent(this).start();
        }

    }
    @Click
    void btn_account(View v) {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).startForResult(REQUEST_CODE);
        } else {
            // update();
            UserSettingActivity_.intent(this).startForResult(AN_REQUEST_CODE);
        }

    }

    @Click
    void btn_comments() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_COMMENT).startForResult(REQUEST_CODE);
        } else {
            // update();
            MyCommentsListActivity_.intent(this).start();
        }

    }

    @Click
    void btn_studio_address() {
        StudioListActivity_.intent(this).start();
    }

    @Click
    void btn_about_us() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).startForResult(REQUEST_CODE);
        } else {
            Intent intent = new Intent();
            intent.putExtra("url", webhost + "/Home/Index/about");
            intent.setClass(this, ShowWebView_.class);
            startActivity(intent);
        }


    }


    @Click
    void btn_ads() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_PROMOTION).startForResult(REQUEST_CODE);
        } else {
            String key = StringEncrypt.Encrypt("mobile=" + pref.loginID().get() + "&key=3e9bb86c6980c3b79e5b936ce10b9b96", "SHA-256");
            Intent intent = new Intent();
//            intent.putExtra("url", "http://share.mlmsalon.com/Home/Partner/index/mobile/" + pref.loginID().get() + "/sign/" + key);
            intent.putExtra("url", webhost + "/Home/Partner/index/mobile/" + pref.loginID().get() + "/sign/" + key);
            intent.putExtra("proxyInfoId", proxyInfoId);
            intent.putExtra("mobile", pref.loginID().get());
            intent.setClass(this, ShowWebView_.class);
            startActivity(intent);
        }


    }

    @Click
    void btn_sign() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_SIGNIN).startForResult(REQUEST_CODE);
        } else {
            String key = StringEncrypt.Encrypt("mobile=" + pref.loginID().get() + "&key=3e9bb86c6980c3b79e5b936ce10b9b96", "SHA-256");
            Intent intent = new Intent();
            intent.putExtra("url", webhost + "/Home/Activity/sign/mobile/" + pref.loginID().get() + "/sign/" + key);
            intent.setClass(this, ShowWebView_.class);
            startActivity(intent);
        }


    }

    @Click
    void btn_order_all() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_ORDERS_ALL).startForResult(REQUEST_CODE);
        } else {
            // update();
            OrdersActivity_.intent(this).extra("flag", OrdersActivity.TYPE_ALL)
                    .start();
        }

    }

    @Click
    void btn_unpay() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_ORDERS_UNPAY).startForResult(REQUEST_CODE);
        } else {
            // update();
            OrdersActivity_.intent(this)
                    .extra("flag", OrdersActivity.TYPE_NONPAY).start();
        }

    }

    @Click
    void btn_appointment_success() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_ORDERS_SUCCESS).startForResult(REQUEST_CODE);
        } else {
            // update();
            OrdersActivity_.intent(this)
                    .extra("flag", OrdersActivity.TYPE_BOOKED).start();
        }

    }

    @Click
    void btn_finished() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_ORDERS_COMPLETE).startForResult(REQUEST_CODE);
        } else {
            // update();
            OrdersActivity_.intent(this)
                    .extra("flag", OrdersActivity.TYPE_FINISH).start();
        }

    }

    @Click
    void btn_payback() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_ORDERS_REFUND).startForResult(REQUEST_CODE);
        } else {
            // update();
            OrdersActivity_.intent(this)
                    .extra("flag", OrdersActivity.TYPE_REFUND).start();
        }

    }

    @Click
    void iv_headimg() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).startForResult(REQUEST_CODE);
        } else {
            dialog = new ActionSheetDialog(this, new String[]{take_photo,
                    from_photos}, null);
            dialog.titleTextColor(red).itemTextColor(blacktext).cornerRadius(0)
                    .show();
            dialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                    switch (position) {
                        case 0:
                            Intent intentFromCapture = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            // 判断存储卡是否可以用，可用进行存储
                            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                    .fromFile(new File(Environment
                                            .getExternalStorageDirectory(),
                                            IMAGE_FILE_NAME)));
                            startActivityForResult(intentFromCapture,
                                    AVATAR_REQUEST_CODE);

                            break;
                        case 1:
                            Intent intentFromGallery = new Intent();
                            intentFromGallery.setType("image/*"); // 设置文件类型
                            intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intentFromGallery,
                                    GALLERY_AVATAR_REQUEST_CODE);
                            break;
                    }
                    dialog.dismiss();
                }
            });
        }
    }

    @OnActivityResult(GALLERY_AVATAR_REQUEST_CODE)
    void onResultGallery(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (data != null) {
            Intent intent = CommonUtils.startPhotoZoom(data.getData());
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        }
    }

    @OnActivityResult(AVATAR_REQUEST_CODE)
    void onResultTakeAvatar(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        File tempFile = new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
        Intent intent = CommonUtils.startPhotoZoom(Uri.fromFile(tempFile));
        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
    }

    @OnActivityResult(PHOTO_PICKED_WITH_DATA)
    void onResultGetAvatar(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (data != null) {
            setImageToView(data);
        }
    }

    /**
     * login request
     *
     * @throws UnsupportedEncodingException
     */
    private void uploadAction(String avatar) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("avatar", avatar));
        // img
        CommonUtils.postRequest(upload_avatar_action, aq, uploadHeadimg, pairs);

    }

    @Receiver(actions = CollectionsActivity.COLLECTION_REFRESH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
    protected void onOrderRefresh(Intent intent) {
        if (intent.getStringExtra("refreshflag") != null && "0".equals(intent.getStringExtra("refreshflag"))) {
            update();
        }
    }

    @Receiver(actions = "point_refresh")
    protected void onPointRefresh(Intent intent) {
        update();
    }


    private void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            String temp = "";
            try {
                temp = CommonUtils.encodeBase64File(CommonUtils
                        .saveBitmap(photo));
                File tempFile = new File(Environment.getExternalStorageDirectory(),
                        IMAGE_FILE_NAME);
                tempFile.delete();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            uploadAction(temp);
        }
    }

    @Click
    void ll_collection() {
        if ("0".equals(pref.loginID().get())) {
            LoginActivity_.intent(this).extra("forward_type",FORWARD_TYPE_COLLECTION).startForResult(REQUEST_CODE);
        } else {
            // update();
            CollectionsActivity_.intent(this).start();
        }

    }

    @Click
    void btn_home() {
        MainActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_dresser() {
        HairDresserListActivity_.intent(this).extra("bookflag",false).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_appointment() {
        BookActivity_.intent(this).start();
    }

    @Click
    void btn_style() {
        HairStyleListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @ViewById
    Button btn_userinfo;

    @Click
    void btn_userinfo() {
        // UserInfoActivity_.intent(this).start();

    }
    private long exitTime = 0;
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        if((System.currentTimeMillis()-exitTime) > 2000){
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finishApplication();
        }
    }

}
